﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="author" content="Cheresting" />
  <!-- 自动添加dayjs到全局 -->
  <script src="./publicJs/dayjs.min.js"></script>
  <!-- 自动添加vue到全局 -->
  <script src="./publicJs/vue.global.prod.js"></script>
  <!-- 自动添加axios到全局 -->
  <script src="./publicJs/axios.min.js"></script>
  <!-- 自动添加Cookies到全局 -->
  <script src="./publicJs/js.cookie.min.js"></script>
  <!-- 自动添加XLSX到全局 -->
  <script src="./publicJs/xlsx.core.min.js"></script>

  <link rel="stylesheet" href="./publicJs/element-plus.index.css" />
  <!-- 自动添加ElementPlus到全局 -->
  <script src="./publicJs/element-plus.index.full.js"></script>
  <script src="./publicJs/index.iife.min.js"></script>
  <!-- 自动添加VXE到全局 -->
  <link rel="stylesheet" href="./publicJs/vxe/ui.style.min.css" />
  <link rel="stylesheet" href="./publicJs/vxe/table.style.min.css" />
  <script src="./publicJs/vxe/xe-utils.umd.min.js"></script>
  <script src="./publicJs/vxe/ui.index.umd.min.js"></script>
  <script src="./publicJs/vxe/table.index.umd.min.js"></script>

  <title>电机进料检验单查询</title>
</head>

<body>
  <div id="app">
    <div v-loading="loading">
      <div>



      </div>
      <div style="height: 90vh;margin-top: 10px;">
        <vxe-toolbar ref="toolbarRef" custom>
          <template #buttons>
            <vxe-date-range-picker v-model="valDate" clearable @change="handleDateChange"></vxe-date-range-picker>
            <vxe-button @click="click1" style="margin-left: 10px;">查询</vxe-button>
            <vxe-button @click="printEvent">打印</vxe-button>
            <vxe-button @click="togglePrintAgain">
              关闭/开启已打印重复选择
            </vxe-button>
            <vxe-input style="margin-left: 10px;" v-model="filterName" type="search" placeholder="搜索" clearable
              @change="searchEvent"></vxe-input>
          </template>
        </vxe-toolbar>
        <vxe-table :checkbox-config="{ checkMethod }" :print-config="printConfig" ref="tableRef" border height="100%"
          id="tableView1" :custom-config="{storage: true}" :column-config="{resizable: true,useKey:true}"
          :row-config="{useKey:true}" :virtual-y-config="{enabled: true, gt: 0}" :data="list"
          :row-class-name="tableRowClassName">
          <vxe-column type="checkbox" width="60" align="center"></vxe-column>
          <vxe-column type="seq" width="60" align="center"></vxe-column>
          <vxe-column v-for="column in tableColumns" type="html" :key="column.field" :field="column.field"
            :title="column.title" :width="column.width" :sortable="column.sortable" align="center">
          </vxe-column>
          <vxe-column field="PRINTCHECK" width="100" align="center" :filters="printOptions" title="状态"></vxe-column>
          <vxe-column field="control" title="操作" width="160" align="center">
            <template #default="{ row }">
              <vxe-button @click="checkSelf(row.QA_IQCRECORDID)"
                :disabled="!(row.PRINTCHECK === '未处理' || printAgain.value)">点击手动完成</vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</body>
<script type="module">
  import myAxios from './myAxios/myAxios.js'
  import myAxiosWXPost from './myAxios/myAxiosWXPost.js'
  import { showSuccess, showWarning } from './hooks/useMyMessageBox.js'
  import v4 from './publicJs/uuidv4.js'
  const { createApp, ref, reactive, computed, onMounted, nextTick, watch } = Vue
  const { Bottom, Top, Right, Delete, Refresh, Calendar, Check, Search } = ElementPlusIconsVue

  import { GetMatCodeParamString } from './QDQZJH_JS/getMatCodeParamString.js'
  import { GetDataList2 } from './QDQZJH_JS/GetDataList2.js'

  const app = createApp({
    name: 'djjljydcx',
    components: {},
    setup() {
      let loading = ref(false)
      let tableRef = ref()
      let toolbarRef = ref()
      const filterName = ref('')
      const list = ref([])
      const startDate = ref('')
      const endDate = ref('')
      const tableData = ref([])
      const filterData = ref([])
      const printAgain = ref(false)
      const togglePrintAgain = () => {
        printAgain.value = !printAgain.value
      }

      const checkMethod = ({ row }) => {

        return row.PRINTCHECK !== '已处理' || printAgain.value // 只有不是“已打印”的行才能被选中
      }
      const tableRowClassName = ({ row }) => {

        if (row.PRINTCHECK !== '未处理' && row.PRINTCHECK) {
          return 'highlight-row'
        }
        return ''
      }

      const getLast7DaysRange = () => {
        const today = new Date()
        const startDate = new Date()
        startDate.setDate(today.getDate() - 7) // 前7天

        const formatDate = (date) => {
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          return `${year}-${month}-${day}`
        }

        return [formatDate(startDate), formatDate(today)]
      }

      // 设置默认值
      const valDate = ref(getLast7DaysRange())
      const formatDate = (dateStr) => {
        if (!dateStr) return ''
        return dateStr.replace(/-/g, '/')
      }
      const handleDateChange = (value) => {

        for (let i in valDate.value) {
          console.log(formatDate(valDate.value[i]));
        }


      }
      let getTableDataByDate = function () {
        let params = `${formatDate(valDate.value[0])}🈹${formatDate(valDate.value[1])}`;
        console.log('valDate.value>>', valDate.value)
        let name = '乐昊查询电机已检验未入库'
        myAxios
          .get(name, params, '9900')
          .then((res) => {
            if (res instanceof Array) {
              tableData.value = res;
              generateColumns(tableData.value)
              handleSearch()
              console.log('tableData :>> ', tableData);
            } else {
              console.log('params :>> ', params);
              showWarning('获取数据失败res!' + res)
            }

          })
          .catch((err) => {

            showWarning('获取数据失败err!' + err)
          })

      }

      let updateStates = function (Array) {
        let params = '';
        for (let i of Array) {
          params = `${i}`;
          let name = '丁允鑫进料检验单打印状态插入'
          myAxios
            .post(name, params, '9900')
            .then((res) => {
              if (res) {

                console.log('插入数据', params, ',res>>', res)
              } else {
                showWarning('插入数据失败res!' + res)
              }

            })
            .catch((err) => {

              showWarning('插入数据失败err!' + err)
            })
        }
      }
      let checkSelf = function (id) {
        // console.log('id>>>>>>>', id)
        let params = `${id}`;
        let name = '丁允鑫进料检验单打印状态插入'
        myAxios
          .post(name, params, '9900')
          .then((res) => {
            if (res) {
              getTableDataByDate();

              console.log('插入数据', params, ',res>>', res)
            } else {
              showWarning('插入数据失败res!' + res)
            }

          })
          .catch((err) => {

            showWarning('插入数据失败err!' + err)
          })

      }
      let tableColumns = ref([])
      const generateColumns = (data) => {

        if (!data || data.length === 0) {
          tableColumns.value = []
          return
        }

        const keys = Object.keys(data[0]).filter(key =>
          !['REMARK', 'QA_IQCRECORDID', 'PRINTCHECK'].includes(key)
        );


        tableColumns.value = keys.map(key => {
          const column = {
            field: key,
            title: getColumnTitle(key),
            width: getColumnWidth(key),
            sortable: true
          }



          return column
        })
      }
      const click1 = async () => {
        getTableDataByDate()
      }

      const printConfig = reactive({
        sheetName() {
          return `打印标题${Date.now()}`
        }
      })

      let getColumnTitle = (field) => {
        const titleMap = {
          JYSN: '检验单号',
          JODNO: '送货单号',
          MATCODE: '物料号',
          MATNAME: '物料描述',
          RECEIVEQTY: '收货数',
          GOODQTY: '合格数',
          BADQTY: '不合格数',
          SAPQTY: 'SAP收货数',
          SUPPNAME: '供应商',
          WLTYPE: '物料类型',
          CREATETIME: '检验日期',
          CREATOR: '检验员',
          PRINTCHECK: '是否打印',

        }
        return titleMap[field] || field
      }
      let getColumnWidth = (field) => {
        // 根据字段类型设置不同的列宽
        if (['JYSN', 'CREATETIME'].includes(field)) return 150
        if (['JODNO'].includes(field)) return 120
        if (['RECEIVEQTY', 'GOODQTY', 'BADQTY', 'SAPQTY'].includes(field)) return 70
        if (field === 'MATNAME') return 140
        if (field === 'MATCODE') return 100
        return 100
      }


      const handleSearch = () => {
        const filterVal = String(filterName.value).trim().toLowerCase()
        if (filterVal) {
          const filterRE = new RegExp(filterVal, 'gi')
          const searchProps = ['JYSN', 'CREATOR', 'JODNO', 'MATCODE', 'MATNAME', 'WLTYPE', 'SUPPNAME']
          const rest = tableData.value.filter(item => searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1))
          list.value = rest.map(row => {
            // 搜索为克隆数据，不会污染源数据
            const item = XEUtils.clone(row)
            searchProps.forEach(key => {
              item[key] = String(item[key]).replace(filterRE, match => `<span class="keyword-highlight">${match}</span>`)
            })
            return item
          })
        } else {
          list.value = tableData.value
        }
      }
      // 节流函数,间隔500毫秒触发搜索
      const searchEvent = XEUtils.throttle(function () {
        handleSearch()
      }, 500, { trailing: true, leading: true })

      const printEvent = async () => {
        const $table = tableRef.value
        const selectedRows = $table.getCheckboxRecords()
        // console.log('selectedRows>>>', selectedRows)
        // console.log("$table>>>>>>>>>>>>>", $table)
        if (!selectedRows.length) {
          alert('请选择数据')
          return
        }

        const recordIds = selectedRows.map(r => r.QA_IQCRECORDID)

        // 更新数据库
        updateStates(recordIds)
        // // 更新前端状态
        // await getTableDataByDate();
        // handleSearch();
        // 打开打印
        $table.openPrint()

      }

      const printOptions = ref([
        { label: '未处理', value: '未处理' },
        { label: '已处理', value: '已处理' }
      ])



      onMounted(async () => {
        await getTableDataByDate()
        handleSearch()
        const $table = tableRef.value
        const $toolbar = toolbarRef.value
        if ($table && $toolbar) {
          $table.connect($toolbar)
        }


      },
      )
      return {
        checkSelf,
        filterName, list, handleSearch, searchEvent, checkMethod,
        printOptions,
        click1, getColumnWidth, printEvent, updateStates, tableRowClassName, togglePrintAgain,
        loading, printAgain,
        tableRef, toolbarRef,
        tableData, filterData,
        tableColumns,
        valDate,
        handleDateChange, getTableDataByDate, getColumnTitle,
        printConfig,
      }
    },
  })

  app.use(ElementPlus)
  app.use(VxeUI)
  app.use(VxeUITable)
  app.mount('#app')
</script>
<style>
  .marginTop10 {
    margin-top: 10px;
  }

  .keyword-highlight {
    background-color: #ffff00;
  }

  .highlight-row {
    background-color: #b7e7b7 !important;
    color: #000;
  }
</style>

</html>